package com.yonyou.gmmc.service.SAInterface.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.marketing.common.FrameHttpUtil;
import org.marketing.common.dms.http.HttpCommonUtil;
import org.marketing.common.dto.customerInfo.CarInfoDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.yonyou.gmmc.service.SAInterface.constant.SAInterfaceConstant;
import com.yonyou.gmmc.service.SAInterface.dao.SAInterfaceMapper;
import com.yonyou.gmmc.service.SAInterface.model.ResultOwnerAuthenticate;
import com.yonyou.gmmc.service.SAInterface.model.TmCreateQrCode;
import com.yonyou.gmmc.service.SAInterface.model.TmCarInfoTemp;
import com.yonyou.gmmc.service.SAInterface.util.JsonHelper;

import net.sf.json.JSONObject;

/**
 * SA移动化接口业务类
 * 
 * @author
 *
 */
@Service
public class SAinterfaceService {

	// 注入mapper接口
	@Autowired
	private SAInterfaceMapper saInterfaceMapper;

	@Autowired
	SAServiceInterface customerServiceInterface;
	
	@Value("${DCMS-url}")
	private String dcmsUrl; //读取配置文件路径地址

	private Logger logger = Logger.getLogger(SAInterfaceConstant.class);

	/**
	 * 根据VIN码生成二维码
	 */
	public Map<String, Object> GenerateQrCode(Map<String, Object> map) {
		Map<String, Object> QrCodeUrl = new HashMap<String, Object>();
		String vin = map.get("vin").toString();
		String engine = map.get("engine").toString();
		String phone = map.get("phone").toString();
		String dealerCode = map.get("dealerCode").toString();
		try {
			if ((vin != null && !("".equals(vin))) && (engine != null && !("".equals(engine)))
					&& (phone != null && !("".equals(phone)))
					&& (dealerCode != null && !("".equals(dealerCode)))) {
				//校验字符
				String regex = "(\\+\\d+)?1[34578]\\d{9}$"; //手机号码
				Pattern pattern=Pattern.compile(regex);
				Matcher mat=pattern.matcher(phone);
				//校验手机号码格式
				if(mat.matches()){
					//校验经销商编码是否存在
					Integer tmDealer=saInterfaceMapper.findByDealerCode(dealerCode);
					if(tmDealer>0){
						// 根据VIN码和ENGINE码判断该车辆是否存在菱悦会系统
						List<CarInfoDto> list = findByCat(vin, engine);
						if (list == null || list.size() == 0) {
							// 不存在该车辆
							logger.info("车辆不存在");
							// 调用DCMS接口查询车辆相关信息
							Map<String, Object> result = selectByCat(vin, engine);
							if(result!=null){
								@SuppressWarnings("unchecked")
								List<ResultOwnerAuthenticate> authenticate = (List<ResultOwnerAuthenticate>) result.get("param");
								// 获得车辆完整车架号，发动机号，经销商码
								String Qrvin = authenticate.get(0).getVin();  
								String Qrengine = authenticate.get(0).getEngineNO();
								// 请求执行二维码生成方法
								Map<String, Object> Qrresult = checkoutQrCode(Qrvin, Qrengine, phone, dealerCode);
								if (Qrresult.get("state").equals(SAInterfaceConstant.STATE_CODE_ABNORMAL)) {
									QrCodeUrl.put("url", Qrresult.get("url").toString());
									QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_ABNORMAL); // 状态码
									QrCodeUrl.put("message", "该车辆已经生成二维码！");
								} else if(Qrresult.get("state").equals(SAInterfaceConstant.STATE_CODE_DEFEATED)){
									QrCodeUrl.put("url", "null");
									QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED); // 状态码
									QrCodeUrl.put("message", Qrresult.get("message").toString());
								}else{
									QrCodeUrl.put("url", Qrresult.get("url").toString());
									QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_SUCCEED); // 状态码
									QrCodeUrl.put("message", Qrresult.get("message").toString());
								}
							}else{
								logger.info("查询的车辆信息不存在");
								QrCodeUrl.put("url", "null");
								QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED); // 状态码
								QrCodeUrl.put("message", "车辆信息不存在或者该车辆尚未实销！");
							}
							
						} else { // 存在车辆
									// 根据车辆iD查看绑定情况
							List<CarInfoDto> CarDto = findByBindingCat(list.get(0).getCarId());
							if (CarDto == null || CarDto.size() == 0) {
								// 车辆未绑定
								logger.info("该车辆未被绑定");
								// 调用方法查询DCMS接口获得车辆信息
								Map<String, Object> result = selectByCat(vin, engine);
								if(result!=null){
									if (result.get("falg").toString().equals("0") && result.get("param").toString().equals("null")) {
										QrCodeUrl.put("url", null);
										QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_ABNORMAL); // 状态码
										QrCodeUrl.put("message", "该车辆不符合规则！");
									} else {
										@SuppressWarnings("unchecked")
										List<ResultOwnerAuthenticate> authenticate = (List<ResultOwnerAuthenticate>) result
												.get("param");
										// 获得车辆完整车架号，发动机号，经销商码
										String Qrvin = authenticate.get(0).getVin();
										String Qrengine = authenticate.get(0).getEngineNO();
										// 请求执行二维码生成方法
										Map<String, Object> Qrresult = checkoutQrCode(Qrvin, Qrengine, phone, dealerCode);
										if (Qrresult.get("state").equals(SAInterfaceConstant.STATE_CODE_SUCCEED)) {
											QrCodeUrl.put("url", Qrresult.get("url").toString());
											QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_SUCCEED); // 状态码
											QrCodeUrl.put("message", Qrresult.get("message").toString());
										}else if(Qrresult.get("state").equals(SAInterfaceConstant.STATE_CODE_ABNORMAL)){
											QrCodeUrl.put("url", Qrresult.get("url").toString());
											QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_ABNORMAL); // 状态码
											QrCodeUrl.put("message", Qrresult.get("message").toString());
										}else {
											QrCodeUrl.put("url", null);
											QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED); // 状态码
											QrCodeUrl.put("message", Qrresult.get("message").toString());
										}
									}
								}else {
									logger.info("查询的车辆信息不存在");
									QrCodeUrl.put("url", "null");
									QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED); // 状态码
									QrCodeUrl.put("message", "车辆信息不存在或者该车辆尚未实销！");
								}
								
							} else {
								logger.info("该车辆已被绑定");
								// 车辆已绑定
								QrCodeUrl.put("url", null);
								QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_ABNORMAL); // 状态码
								QrCodeUrl.put("message", "该车辆已被绑定！");
							}
						}		
					}else {
						logger.info("经销商编码不存在！");
						QrCodeUrl.put("url", null);
						QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED); // 状态码
						QrCodeUrl.put("message", "经销商编码不存在！");
					}
				}else {
					logger.info("手机号码格式不正确！");
					QrCodeUrl.put("url", null);
					QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED); // 状态码
					QrCodeUrl.put("message", "手机号码格式不正确！");
				}
			} else {
				logger.info("传入参数为空,二维码生成失败");
				QrCodeUrl.put("url", null);
				QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED); // 状态码
				QrCodeUrl.put("message", "vin为空，二维码生成失败！");
			}
		} catch (Exception e) {
			logger.info("二维码生成失败",e);
			QrCodeUrl.put("url", null);
			QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED);
			QrCodeUrl.put("message", "二维码生成失败");
			 Map<String, Object> exMap = new HashMap<>();
	            exMap.put("openId", engine);
	            exMap.put("type", "SA1");
	            exMap.put("message", "二维码生成失败");
	            exMap.put("vin", vin);
	            exMap.put("exception", e.getMessage());
	            saInterfaceMapper.saveException(exMap);
		}

		return QrCodeUrl;
	}


	/**
	 * 生成二维码校验
	 */
	public Map<String, Object> checkoutQrCode(String vin, String engine, String phone, String dealerCode) {
		Map<String, Object> QrCodeUrl = new HashMap<String, Object>();
		try {
			logger.info("开始调用生成二维码");
			// 根据vin码查询是否已生成二维码
			TmCreateQrCode qrCode = findByTicket(vin);
			// 判断是否已存在二维码，不存在则请求新增
			if (qrCode != null && !("".equals(qrCode))) {
				// 判断是否时间过期
				Date createDate = qrCode.getCreateTime();
				Date date = new Date();
				long daysBetween = (date.getTime() - createDate.getTime()) / (3600 * 24 * 1000);
				if (daysBetween < 30) {
					String codeUrl = SAInterfaceConstant.QR_CODE_TICKET + qrCode.getTicket();
					QrCodeUrl.put("url", codeUrl);
					QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_ABNORMAL); // 状态码
					QrCodeUrl.put("message", "该车辆已生成指定二维码");
				} else {
					String codeUrl = getByToken(vin, engine, phone, dealerCode); // 请求获得tocken码
					String ticket = codeUrl.substring(codeUrl.indexOf("=") + 1, codeUrl.length());
					TmCreateQrCode code = new TmCreateQrCode();
					code.setVin(vin);
					code.setTicket(ticket);
					code.setCreateTime(new Date());
					// 调用更新记录表信息
					updateTicket(code);
					QrCodeUrl.put("url", codeUrl);
					QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_ABNORMAL); // 状态码
					QrCodeUrl.put("message", "原二维码已失效！重新返回新二维码");
				}
			} else {
				String codeUrl = getByToken(vin, engine, phone, dealerCode); // 请求获得tocken码
				if (codeUrl != null && !("".equals(codeUrl))) {
					String ticket = codeUrl.substring(codeUrl.indexOf("=") + 1, codeUrl.length());
					// 定义记录表对象
					TmCreateQrCode code = new TmCreateQrCode();
					code.setVin(vin);
					code.setTicket(ticket);
					code.setCreateTime(new Date());
					code.setCreateBy(SAInterfaceConstant.OPERATION_BY);
					code.setCreateDate(new Date());
					code.setUpdateBy(SAInterfaceConstant.OPERATION_BY);
					code.setUpdateDate(new Date());
					// 调用增加记录表信息
					saveTicket(code);
					QrCodeUrl.put("url", codeUrl);
					QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_SUCCEED); // 状态码
					QrCodeUrl.put("message", "返回二维码成功");
					logger.info("返回二维码地址成功============"+QrCodeUrl);
				} else {
					QrCodeUrl.put("url", null);
					QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED); // 状态码
					QrCodeUrl.put("message", "返回二维码失败");
					logger.info("返回二维码失败或请求异常");
				}
			}
		} catch (Exception e) {
			logger.error(new Exception(e));
			QrCodeUrl.put("url", null);
			QrCodeUrl.put("state", SAInterfaceConstant.STATE_CODE_DEFEATED);
			QrCodeUrl.put("message", "二维码校验数据异常");
		}
		return QrCodeUrl;
	}

	/**
	 * 请求服务器获得token码
	 */
	public String getByToken(String vin, String engine, String phone, String dealerCode) {
		String Codeurl = null;
		logger.info("开始获得token码");
		try {
			// 查询数据库token码
			// String token=selectByToken();
			String token = customerServiceInterface.genToken(); // 调用接口查询token
			JSONObject jso=JsonHelper.strToJson(token);
			Map<String, Object>ww=JsonHelper.json2Map(jso); 
			  String tokens=ww.get("token").toString();
			// 向微信数据库发送post请求
			logger.info("查询的token========="+token);
			String url = SAInterfaceConstant.WECHAT_QR_CODE + tokens;
			String param = "{\"action_info\": {\"scene\": {\"scene_str\": \"PARAMS\"}},\"action_name\": \"QR_STR_SCENE\",\"expire_seconds\": \"2592000\"}";
			param = param.replaceAll("PARAMS", vin + "@"+ engine + "@" + phone + "@" + dealerCode);
			logger.info("传入二维码参数==========="+param);
			// 调用工具类post请求方法发送请求参数
			String strTicket = FrameHttpUtil.post(url, param);
			logger.info("调用接口发送微信请求完毕的返回值 >>>>>>>>>"+strTicket);
			if (strTicket != null && !("".equals(strTicket))) {
				// 调用解析方法获取ticket码并返回结果
				Codeurl = AnalysisTicket(strTicket);
			} else {
				logger.info("返回参数异常！请求微信服务器获得二维码ticket失败！");
			}
		} catch (Exception e) {
			logger.error("获得token失败，请求异常！", e);
			return null;
		}
		return Codeurl;
	}

	/**
	 * 解析微信服务器返回的json格式数据获取ticket码
	 * 
	 * @param strTicket
	 * @return
	 */
	public String AnalysisTicket(String strTicket) {
		String qrUrl = null;
		try {
			logger.info("开始解析返回值======="+strTicket);
			if (strTicket != null && !("".equals(strTicket))) {
				JSONObject object = JSONObject.fromObject(strTicket);
				// 将json格式转换为map集合
				Map<String, Object> map = JsonHelper.json2Map(object);
				String ticket = (String) map.get("ticket");
				qrUrl = SAInterfaceConstant.QR_CODE_TICKET + ticket;
			} else {
				logger.info("传入数据为空，解析失败");
			}
		} catch (Exception e) {
			logger.error("解析二维码返回数据失败！", e);
			return null;
		}
		return qrUrl;
	}

	/**
	 * 根据vin码查询二维码记录表信息
	 * 
	 * @param vin
	 * @return
	 */
	public TmCreateQrCode findByTicket(String vin) {
		TmCreateQrCode code = null;
		logger.info("查询二维码记录信息");
		try {
			if (vin != null) {
				code = saInterfaceMapper.getByTicket(vin);
				if (code == null) {
					return null;
				}
			} else {
				logger.info("传入VIN码为空！查询失败");
			}
		} catch (Exception e) {
			logger.error("二维码生成信息查询失败", e);
		}
		return code;
	}

	/**
	 * 更新二维码记录表关键信息
	 * 
	 * @param code
	 */
	public void updateTicket(TmCreateQrCode code) {
		logger.info("更新二维码信息表");
		try {
			if (code != null) {
				saInterfaceMapper.changeTicket(code);
			} else {
				logger.info("传入参数为空，更新失败");
			}
		} catch (Exception e) {
			logger.error("更新二维码信息错误", e);
		}

	}

	/**
	 * 保存二维码记录表信息
	 * 
	 * @param code
	 */
	public void saveTicket(TmCreateQrCode code) {
		logger.info("开始保存二维码记录信息");
		try {
			if (code != null) {
				saInterfaceMapper.addTicket(code);
			}
		} catch (Exception e) {
			logger.error("二维码信息记录失败", e);
		}
	}

	/**
	 * 根据VIN码查询车辆是否存在菱悦会系统
	 */
	public List<CarInfoDto> findByCat(String vin, String engine) {
		List<CarInfoDto> list = null;
		try {
			logger.info("查询车辆是否存在");
			if (vin != null) {
				list = saInterfaceMapper.selCarInfoByVin(vin, engine);
			} else {
				logger.info("车辆VIN为空");
			}
		} catch (Exception e) {
			logger.error("车辆信息查询失败", e);
		}
		return list;
	}

	/**
	 * 根据VIN码查询车辆绑定情况
	 * 
	 */
	public List<CarInfoDto> findByBindingCat(Long catId) {
		logger.info("查询车辆绑定关系");
		List<CarInfoDto> CarDto = null;
		try {
			if (catId != null) {
				CarDto = saInterfaceMapper.getCarInfoByCarId(catId);
			} else {
				logger.info("车辆Id为空");
				return null;
			}
		} catch (Exception e) {
			logger.error("车辆绑定信息查询失败", e);
		}
		return CarDto;
	}

	
	
	/**
	 * 调用DCMS系统接口根据VIN码查询车辆信息
	 */
	public Map<String, Object> selectByCat(String vin, String engine) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		List<ResultOwnerAuthenticate> resultDto = null;
		try {
			if (vin != null) {
				map.put("vin", vin);
				map.put("engine", engine);
				String url = SAInterfaceConstant.VININFO_URL.replaceAll("172.16.97.153:7001", dcmsUrl);
				// 调用DCMS系统接口
				resultDto = HttpCommonUtil.getOwnerInfo(map, "ID001", url, ResultOwnerAuthenticate.class);
				logger.info("调用DCMS接口完毕");
				//logger.info("================size"+resultDto.size());
				if (resultDto != null && resultDto.size() > 0) {
					// 保存车辆信息
					for (ResultOwnerAuthenticate resultList : resultDto) {
						TmCarInfoTemp tmSaCatInfo = new TmCarInfoTemp();
						tmSaCatInfo.setProductionDate(
								resultList.getProductionDate() == null ? new Date() : resultList.getProductionDate());
						tmSaCatInfo.setDeliveryDate(
								resultList.getDeliveryDate() == null ? new Date() : resultList.getDeliveryDate());
						tmSaCatInfo.setVin(resultList.getVin() == null ? "" : resultList.getVin());
						tmSaCatInfo.setEngine(resultList.getEngineNO() == null ? "" : resultList.getEngineNO());
						tmSaCatInfo.setModelCodeNew(resultList.getModelCode() == null ? "" : resultList.getModelCode());
						tmSaCatInfo
								.setBillDate(resultList.getBillDate() == null ? new Date() : resultList.getBillDate());
						tmSaCatInfo.setProvince(resultList.getProvince() == null ? 0 : resultList.getProvince());
						tmSaCatInfo.setCity(resultList.getCity() == null ? 0 : resultList.getCity());
						tmSaCatInfo.setAddress(resultList.getAddress() == null ? "" : resultList.getAddress());
						tmSaCatInfo.setZip(resultList.getZip() == null ? "" : resultList.getZip());
						tmSaCatInfo.setLinkMan(resultList.getLinkMan() == null ? "" : resultList.getLinkMan());
						tmSaCatInfo.setSex(resultList.getSex() == null ? 0 : resultList.getSex());
						tmSaCatInfo.setBuyerTel(resultList.getTel() == null ? "" : resultList.getTel());
						tmSaCatInfo.setPhone(resultList.getPhone() == null ? "" : resultList.getPhone());
						tmSaCatInfo.setEmail(resultList.getEmail() == null ? "" : resultList.getEmail());
						tmSaCatInfo.setOtherLinkWay(
								resultList.getOtherLinkWay() == null ? "" : resultList.getOtherLinkWay());
						tmSaCatInfo.setCredentialsType(
								resultList.getCredentialsType() == null ? 0 : resultList.getCredentialsType());
						tmSaCatInfo.setCredentialsNo(
								resultList.getCredentialsNo() == null ? "" : resultList.getCredentialsNo());
						tmSaCatInfo.setLicenseNo(resultList.getLicenseNo() == null ? "" : resultList.getLicenseNo());
						tmSaCatInfo.setDealerCode(resultList.getDealerCode() == null ? "" : resultList.getDealerCode());
						tmSaCatInfo.setAfterSalesCode(
								resultList.getAfterSalesCode() == null ? "" : resultList.getAfterSalesCode());
						tmSaCatInfo.setConsultantName(
								resultList.getConsultantName() == null ? "" : resultList.getConsultantName());
						saInterfaceMapper.savaTmSaCatInfo(tmSaCatInfo);
					}
					result.put("falg", "1");
					result.put("resultMsg", "查询成功");
					result.put("param", resultDto);
					logger.info("车辆信息查询成功");
				} else {
					logger.info("车辆信息不存在或者该车辆尚未实销！");
					result.put("falg", "0");
					result.put("resultMsg", "车辆信息不存在或者该车辆尚未实销！");
					result.put("param", "null");
				}
			} else {
				logger.info("VIN码不能为空！");
				result.put("falg", "0");
				result.put("resultMsg", "VIN码不能为空！");
				result.put("param", "null");
			}
		} catch (Exception e) {
			logger.error("调用DCMS接口查询车辆信息错误", e);
			result.put("falg", "0");
			result.put("resultMsg", "查询车辆信息错误");
			result.put("param", "null");
			Map<String, Object> exMap = new HashMap<>();
            exMap.put("openId", engine);
            exMap.put("type", "1");
            exMap.put("message", "调用DCMS接口查询车辆信息错误");
            exMap.put("vin", vin);
            exMap.put("exception", e.getMessage());
            saInterfaceMapper.saveException(exMap);
		}
		logger.info("res----------------"+result);
		return result;
	}
}
